package com.lab.cloud.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JWTUtils {

    private static final String JWT_KEY = "HowBeautifulYouAreHowBeautifulYouAreHowBeautifulYouAreHowBeautifulYouAre";

    public static JWTToken getJWT(String body, String role) {
        long expires_in = 1000 * 60 * 60 * 24; //一天
        long time = System.currentTimeMillis();
        JwtBuilder builder = Jwts.builder()
                .setId(UUID.randomUUID().toString()) //设置唯一ID
                .setSubject(body) //设置内容，这里用JSON包含帐号信息
                .setIssuedAt(new Date()) //签发时间
                .setExpiration(new Date(time + expires_in)) //过期时间
                .claim("roles", role) //设置角色
                .signWith(SignatureAlgorithm.HS256, generalKey()) //设置签名 使用HS256算法，并设置密钥
                ;
        String code = builder.compact();
        JWTToken token = JWTToken.builder()
                .access_token(code)
                .expires_in(expires_in / 1000)
                .token_type("JWT")
                .build();
        return token;
    }

    public static Claims parseJWT(String jwt) {
        Claims body = Jwts.parser().setSigningKey(generalKey()).parseClaimsJws(jwt).getBody();
        return body;
    }

    public static JWTToken refreshJWT(String jwt) {
        Claims claims = parseJWT(jwt);
        String body = claims.getSubject();
        String role = claims.get("roles").toString();
        return getJWT(body, role);
    }

    public static Claims infoJWT(String jwt) {
        Claims claims = parseJWT(jwt);
        return claims;
    }

    public static boolean checkJWT(String jwt) {
        try {
            Claims body = Jwts.parser().setSigningKey(generalKey()).parseClaimsJws(jwt).getBody();
            if (body != null) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
}